package com.molichuxing.gateway.api.services.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.molichuxing.gateway.api.services.WechatpayApiService;
import com.molichuxing.gateway.bff.order.services.OrderBffService;
import com.molichuxing.gateway.bff.payment.services.WechatpayBffService;
import com.molichuxing.services.business.dto.response.NotifyBizDto;
import com.molichuxing.services.property.PaymentResultEnum;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "微信支付回调api")
@RestController
@RequestMapping(value = "/wechatpay")
public class WechatpayApiServiceImpl extends RootApiService implements WechatpayApiService {
	private static final Logger logger = LoggerFactory.getLogger(WechatpayApiServiceImpl.class);

	@Resource
	private WechatpayBffService wechatpayBffService;

	@Resource
	private OrderBffService orderBffService;

	@Override
	@ApiOperation(value = "微信支付结果通知")
	@PostMapping(value = "/notify/pay")
	public void notifyPay(HttpServletRequest request, HttpServletResponse response) {
		OutputStream out = null;
		try {
			String xmlStr = getResponseXml(request);
			logger.info("[notifyPay]微信支付结果: ({})", xmlStr);
			if (StringUtils.isBlank(xmlStr)) {
				return;
			}
			NotifyBizDto notifyBizDto = wechatpayBffService.modifyNotifyPay(xmlStr);
			if (PaymentResultEnum.SUCCESS.equals(notifyBizDto.getPayResult())) {
				// 成功，修改订单信息(异步)
				orderBffService.modifyOrderPay(notifyBizDto);
			}

			// 返回微信SUCCESS
			out = response.getOutputStream();
			String xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
			out.write(xml.getBytes("UTF-8"));
			out.flush();
		} catch (Exception e) {
			logger.error("微信支付结果通知异常:", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					out = null;
				}
			}
		}
	}

	/**
	 * 获取微信通知信息
	 *
	 * @param request
	 * @return
	 * @throws IOException
	 */
	private String getResponseXml(HttpServletRequest request) throws IOException {
		InputStream inputStream = null;
		BufferedReader bufferedReader = null;
		StringBuffer stringBuffer = null;
		try {
			// post 过来的xml
			inputStream = request.getInputStream();
			bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			stringBuffer = new StringBuffer();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line);
			}
			return stringBuffer.toString();
		} catch (IOException e) {
			throw e;
		} finally {
			if (stringBuffer != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
					bufferedReader = null;
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
					inputStream = null;
				}
			}
		}
	}
}
